package com.fw.ui.core;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.vaadin.server.UIClassSelectionEvent;
import com.vaadin.server.UICreateEvent;
import com.vaadin.server.UIProvider;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;

public class SpringUIProvider extends UIProvider {

    private static final long serialVersionUID = -1520300392770188132L;

    @Override
    public UI createInstance(UICreateEvent event) {
	try {
	    WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(VaadinServlet.getCurrent()
		    .getServletContext());
	    return applicationContext.getBean(event.getUIClass());
	} catch (Exception e) {
	    throw new RuntimeException("Could not instantiate UI class", e);
	}
    }

    @Override
    public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
	VaadinRequest request = event.getRequest();

	Object uiClassNameObj = request.getService().getDeploymentConfiguration()
		.getApplicationOrSystemProperty(VaadinSession.UI_PARAMETER, null);

	if (uiClassNameObj instanceof String) {
	    String uiClassName = uiClassNameObj.toString();

	    ClassLoader classLoader = request.getService().getClassLoader();
	    try {
		Class<? extends UI> uiClass = Class.forName(uiClassName, true, classLoader).asSubclass(UI.class);

		return uiClass;
	    } catch (ClassNotFoundException e) {
		throw new RuntimeException("Could not find UI class", e);
	    }
	}

	return null;
    }

}
